package com.manage.common.core.utils;

import cn.hutool.json.JSONUtil;
import com.manage.common.core.constants.Constant;
import com.manage.common.core.dto.token.User;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * 请求上下文工具类
 *
 * @author zhangqing
 */
public class ContextHolderUtils {

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static User getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String header = null;
        try {
            header = URLDecoder.decode(request.getHeader(Constant.CURRENT_USER), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return JSONUtil.toBean(header, User.class);
    }

    /**
     * 判断该用户是否是超级管理员用户
     *
     * @param userDto 用户信息
     * @return 如果是, 返回true. else返回false
     */
    public static Boolean isSuperAdmin(User userDto) {
        return userDto.getAuthorities().contains(Constant.ADMIN);
    }

    private static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }
}